// pages/pos/info/view.js
const { wxPost, wxGet, formatTime, commonShare, host, getJwt} = require('../../utils/common.js')
var sMD5 = require('../../utils/spark-md5.js')

const app = getApp()
Page({

  data: {
    waitLoading: true,
    imgs: []
  },
  onLoad: function (options) {
    this.setData({
      albumId: options.albumId || '',
      infoId: options.infoId || ''
    })
    var pages = getCurrentPages()
    var prevPage = pages[pages.length - 2]  //上一个页面
    if (prevPage) {
      let {imgs} = prevPage.data
      // this.setData({
      //   imgs
      // })
    }
  },
  uploadImg: function () {
    const that = this
    wx.chooseImage({
      count: 9,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        var successUp = 0 //成功
        var failUp = 0 //失败
        var length = res.tempFilePaths.length //总数
        var index = 0 //第几张
        var imgs = that.data.imgs||[]
        var img = {}
        let currentIndex = 0
        const uploadStartIndex = imgs.length || 0
        let tempFilesPath = res.tempFiles.length
        if (tempFilesPath + uploadStartIndex > 9) {
          tempFilesPath = 9 - uploadStartIndex
        }
        for (var i = 0; i < tempFilesPath; i++) {
          const fileSize = res.tempFiles[i].size
          wx.getImageInfo({
            src: res.tempFiles[i].path,
            success(infoRes) {
              console.info(infoRes)
              img.imgWidth = infoRes.width
              img.imgHeight = infoRes.height
              img.thumbnail = infoRes.path
              img.review = infoRes.path
              img.size = fileSize
              img.type = 'upload'
              imgs.push(img)
              img = {}
              currentIndex++
            },
            complete() {
              if (currentIndex == length || imgs.length===9) {
                that.setData({
                  imgs: imgs
                })
              
               // console.info(uploadStartIndex,length)
                var pages = getCurrentPages()
                var prevPage = pages[pages.length - 2]  //上一个页面
                setTimeout(()=>{
                  that.uploadOneByOne(uploadStartIndex, imgs.length, (removeArray) => {
                    //console.info(removeArray)
                    if (removeArray && removeArray.length > 0) {
                      const { imgs: _imgs } = that.data
                      for (let x = 0; x < removeArray.length; x++) {
                        _imgs.splice(removeArray[x] - x, 1)
                      }
                      that.setData({
                        imgs: _imgs
                      })
                    }
                  }, [])
                },1)
              }
            }
          })
        }
      }
    })
  },
  uploadOneByOne: function (index, length, doneCallback,removeArray) {
    var that = this
    const tempFiles = that.data.imgs
    if (!tempFiles[index]){
      if (doneCallback) {
        doneCallback(removeArray)
      }
      return 
    }
    if (tempFiles[index].type !=='upload') {
      tempFiles[index].id = tempFiles[index].id
      index++ //下一张
      if (index == length) {
        //上传完毕，作一下提示
        if (doneCallback) {
          doneCallback(removeArray)
        }
      } else {
        //递归调用，上传下一张
        that.uploadOneByOne(index, length, doneCallback, removeArray)
      }
    } else if (tempFiles[index].type === 'upload') {
      const filePath = tempFiles[index].review
      const imgSize = tempFiles[index].size
      const imgWidth = tempFiles[index].imgWidth
      const imgHeight = tempFiles[index].imgHeight
     
      wx.getFileSystemManager().readFile({
        filePath: filePath, //选择图片返回的相对路径
        success: res => {
          var spark = new sMD5.ArrayBuffer()
          spark.append(res.data)
          var hexHash = spark.end(false)
          wx.uploadFile({
            url: `${host}/assetsInfo/feedBackImg/upload`, 
            filePath: filePath,
            name: 'file',
            formData: {
              infoId: that.data.infoId||'',
              albumId:that.data.albumId||'',
              imgSize: imgSize,
              imgWidth: imgWidth,
              imgHeight: imgHeight,
              md5: hexHash
            },
            header: {
              'Authorization': getJwt()
            },
            success(uploadRes) {
              if (uploadRes.statusCode == 200) {
                let uploadData = JSON.parse(uploadRes.data)
                console.info(uploadData)
                if (uploadData && uploadData.errorCode === 0) {
                  let tempImgs = that.data.imgs
                  tempImgs[index].id = uploadData.fileData.id
                  tempImgs[index].thumbnail = uploadData.fileData.thumbnail,
                  tempImgs[index].imgSrc = uploadData.fileData.imgSrc,
                  tempImgs[index].imgHeight = uploadData.fileData.imgHeight,
                  tempImgs[index].imgSize = uploadData.fileData.imgSize,
                  tempImgs[index].imgWidth = uploadData.fileData.imgWidth
                  tempImgs[index].type = 'done'
                  app.globalData.uploadImg = true
                  that.setData({
                    imgs: tempImgs
                  })
                  if(length==index+1){
                    var pages = getCurrentPages()
                    var prevPage = pages[pages.length - 2] //上一个页面              
                    if (prevPage) {
                      prevPage.loadAlbumList()
                    }
                  }
                 
                } else if (uploadData.errorCode === -1){
                  showToast(uploadData['msg']||'图片格式必须为JPG或JPEG!')
                  let tempImgs = that.data.imgs
                  removeArray.push(index)
                }
              }
            },
            complete() {
              index++ //下一张
              if (index == length) {
                //上传完毕
                if (doneCallback) {
                  doneCallback(removeArray)
                }
              } else {
                //递归调用，上传下一张
                //console.info('upload index=' + index)
                that.uploadOneByOne(index, length, doneCallback, removeArray)
              }
            }
          })
        }
      })
    }
  },
  viewPhoto:function(e){
    const index = e.currentTarget.dataset.index
    const { imgs } = this.data
    let urls = [], current
    imgs.forEach((o, i) => {
      urls.push(o.review)
      if (i === index) {
        current = o.review
      }
    })
    wx.previewImage({
      urls,
      current
    })
  },
  removePhoto:function(e){
    const that=this
    const id = e.currentTarget.dataset.id
    if (!id) {
      showToast('图片可能在上传队列中,请稍候再试!')
      return
    }
    if (!that.data.submitFlag) {
      that.setData({ submitFlag: true })
      wx.showModal({
        title: '提示',
        content: '确定要删除吗?',
        success: function (res) {
          if (res.confirm) {
            wx.showLoading({
              title: '请稍等...',
              mask: true
            })
            wxPost('/assetsInfo/feedBackImg/remove', { id }, ({ data }) => {
              wx.hideLoading()
              if (data.errorCode === 0) {
                showToast('删除成功!')
                const {imgs}=that.data
                let index=imgs.findIndex(o=>o.id===id)
                imgs.splice(index,1)
                that.setData({
                  imgs
                })
              }
            }, () => {
              wx.hideLoading()
              showToast('删除失败 请稍后重试!')
            }, () => {
              that.setData({ submitFlag: false })
            })
          } else {
            that.setData({ submitFlag: false })
          }
        },
        fail: () => {
          that.setData({ submitFlag: false })
        }
      })

    } else {
      wx.hideLoading()
    }
  },
  back:function(){
    wx.navigateBack({
      delta:1
    })
  }
})
function showToast(title) {
  wx.showToast({
    title: title || '',
    icon: 'none',
    mask: true,
    duration: 1500
  })
}